document.addEventListener("DOMContentLoaded", function () {
  // 回到顶部按钮
  const backToTopButton = document.getElementById("back-to-top"); //选择按钮

  window.addEventListener("scroll", function () {
    if (window.pageYOffset > 300) {
      // 页面向下滚动超过300px时显示按钮
      backToTopButton.style.display = "block";
    } else {
      backToTopButton.style.display = "none";
    }
  });

  backToTopButton.addEventListener("click", function (e) {
    // 点击按钮时回到顶部
    e.preventDefault();
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  });

  // 评论表单提交
  const commentForm = document.getElementById("comment-form"); //选择评论表单
  if (commentForm) {
    commentForm.addEventListener("submit", function (e) {
      //监听提交事件
      e.preventDefault();

      const name = document.getElementById("name").value;
      const commentText = document.getElementById("comment").value;

      if (name && commentText) {
        const commentsList = document.getElementById("comments-list"); //选择评论列表
        const now = new Date();
        const dateStr = now.toLocaleDateString("zh-CN");
        //构造新评论样式
        const newComment = document.createElement("div");
        newComment.className = "comment";
        newComment.innerHTML = `    
                    <div class="comment-author">
                        <img src="https://via.placeholder.com/50" alt="用户头像">
                        <span>${name}</span>
                    </div>
                    <div class="comment-content">
                        <p>${commentText}</p>
                        <div class="comment-meta">${dateStr}</div>
                    </div>
                `;

        commentsList.appendChild(newComment); //添加新评论到列表

        // 清空表单
        commentForm.reset();

        // 滚动到新评论
        newComment.scrollIntoView({ behavior: "smooth" });
      }
    });
  }

  // 联系表单提交
  const contactForm = document.querySelector(".contact-form");
  if (contactForm) {
    contactForm.addEventListener("submit", function (e) {
      e.preventDefault();

      const name = contactForm.querySelector('input[type="text"]').value;
      const email = contactForm.querySelector('input[type="email"]').value;
      const message = contactForm.querySelector("textarea").value;

      if (name && email && message) {
        alert(`感谢您的留言，${name}！我们会尽快回复您。`);
        contactForm.reset();
      } else {
        alert("请填写所有必填字段！");
      }
    });
  }

  // 订阅表单提交
  const subscribeForm = document.querySelector(".subscribe-form");
  if (subscribeForm) {
    subscribeForm.addEventListener("submit", function (e) {
      e.preventDefault();

      const email = subscribeForm.querySelector('input[type="email"]').value;

      if (email) {
        alert(`感谢订阅！我们已将确认邮件发送至 ${email}`);
        subscribeForm.reset();
      } else {
        alert("请输入有效的邮箱地址！");
      }
    });
  }
});
